﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reactive.Linq;
using System.Linq.Expressions;
using System.Runtime.Serialization;

namespace QbservableCore.Client
{
    public abstract class QbservableBase<T> : IQbservable<T>, IQbservableProvider
    {
        private Expression _expression;

        public QbservableBase(string key)
        {
            _expression = Expression.Constant(new QbservableStub<T>(key));
        }

        public QbservableBase(Expression expression)
        {
            _expression = expression;
        }

        #region IQbservable Members

        Type IQbservable.ElementType
        {
            get { return typeof(T); }
        }

        public Expression Expression
        {
            get { return _expression; }
        }

        IQbservableProvider IQbservable.Provider
        {
            get { return this; } //new QbservableProvider(this); }
        }

        public IQbservable<TResult> CreateQuery<TResult>(Expression expression)
        {
            return OnCreate<TResult>(expression);
        }

        #endregion

        #region IObservable<T> Members

        public abstract IDisposable Subscribe(IObserver<T> observer);

        #endregion


        /// <summary>
        /// Called when [create].
        /// </summary>
        /// <typeparam name="TResult">The type of the result.</typeparam>
        /// <param name="expression">The expression.</param>
        /// <returns></returns>
        protected abstract IQbservable<TResult> OnCreate<TResult>(Expression expression);
    }
}
